#!/usr/bin/env python
# 编写python脚本文件, 批量的静态化商品详情页

# 追加导包路径: 指向apps的商一级
import sys
sys.path.insert(0, "../")


# 加载Django程序
import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'meiduo_mall.settings.dev'

import django
django.setup()

from django.template import loader
from django.conf import settings

from apps.goods.models import SKU
from apps.contents.utils import get_categories
from apps.goods.utils import get_breadcrumb
from apps.goods.utils_goods_specs import get_goods_specs



def generate_static_sku_detail_html(sku):
    """
    静态化商品详情页
    :param sku: 要静态化的sku
    :return: sku_id.html
    """

    # 查询商品分类
    categories = get_categories()

    # 查询面包屑导航
    bread_crumb = get_breadcrumb(sku.category)

    # 查询商品规格
    specs = get_goods_specs(sku)

    # 构造上下文
    context = {
        "categories": categories,  # 商品分类
        "bread_crumb": bread_crumb,  # 面包屑导航
        "sku": sku,  # 商品名称,副标题,价格,图片,总价
        "spu": sku.spu,  # 渲染商品的详情,规格与包装,售后服务
        "specs": specs,  # 渲染商品的规格
    }

    # 将渲染号的详情页面写入到静态文件
    template = loader.get_template('detail.html')
    html_text = template.render(context)
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'detail/' + str(sku.id) + '.html')
    with open(file_path, 'w') as f:
        f.write(html_text)

if __name__ == '__main__':
    # 先遍历出所有的sku
    skus = SKU.objects.all()
    for sku in skus:
        print(sku.id)
        generate_static_sku_detail_html(sku)